Vue.js官網有提供建議的Style Guide,接下來幾天會陸續介紹這些Style Guide,寫出好品質、好維護的程式碼!
E.G.
Vue.component('todo-item', {
// ...
})
export default {
name: 'TodoItem',
// ...
}
data()
是需要回傳物件回去的function。E.G.
Vue.component('some-comp', {
data: function () {
return {
foo: 'bar'
}
}
})
// In a .vue file
export default {
data () {
return {
foo: 'bar'
}
}
}
// It's OK to use an object directly in a root
// Vue instance, since only a single instance
// will ever exist.
new Vue({
data: {
foo: 'bar'
}
})
在開發環境下,如果向一個元件提供格式不正確的prop,Vue 將會有警訊,幫助你發現潛在的錯誤。
E.G.
props: {
status: String
}
// Even better!
props: {
status: {
type: String,
required: true,
validator: function (value) {
return [
'syncing',
'synced',
'version-conflict',
'error'
].indexOf(value) !== -1
}
}
}
E.G.
<ul>
<li
v-for="todo in todos"
:key="todo.id"
>
{{ todo.text }}
</li>
</ul>
v-for
上用v-if
為了要略過列表中一個物件,例如:v-for="user in users" v-if="user.isActive",在這種情況替換一個屬性(比如activeUsers),回傳已略過的列表。
在Day 8有提過為什麼不這麼做!
E.G.
<ul>
<li
v-for="user in activeUsers"
:key="user.id"
>
{{ user.name }}
</li>
</ul>
<ul v-if="shouldShowUsers">
<li
v-for="user in users"
:key="user.id"
>
{{ user.name }}
</li>
</ul>
<template>
<button class="button button-close">X</button>
</template>
<!-- Using the `scoped` attribute -->
<style scoped>
.button {
border: none;
border-radius: 2px;
}
.button-close {
background-color: red;
}
</style>
<template>
<button :class="[$style.button, $style.buttonClose]">X</button>
</template>
<!-- Using CSS modules -->
<style module>
.button {
border: none;
border-radius: 2px;
}
.buttonClose {
background-color: red;
}
</style>
<template>
<button class="c-Button c-Button--close">X</button>
</template>
<!-- Using the BEM convention -->
<style>
.c-Button {
border: none;
border-radius: 2px;
}
.c-Button--close {
background-color: red;
}
</style>
var myGreatMixin = {
// ...
methods: {
$_myGreatMixin_update: function () {
// ...
}
}
}
// Even better!
var myGreatMixin = {
// ...
methods: {
publicMethod() {
// ...
myPrivateFunction()
}
}
}
function myPrivateFunction() {
// ...
}
export default myGreatMixin
明天將會繼續來看看次級的Style Guide有什麼吧!
Resource
Vue.js style-guide